import React from 'react';
import { Upload, message } from 'antd';
import useUploadOss from '@/hooks/useUploadOss';

const UploadWork = props => {
    const [uploadFile] = useUploadOss();
    // 校验上传文件类型
    const checkUpload = (file, fileList) => {
        const { checkFileType = '', checkFileSize = 0, checkFileTypeMsg = null, checkFileSizeMsg = null } = props;

        if (checkFileType.length > 0) {
            const fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
            if (!checkFileType.toLocaleLowerCase().includes(fileType.toLocaleLowerCase())) {
                if (checkFileTypeMsg) {
                    message.error(checkFileTypeMsg);
                } else {
                    message.error(`You can only upload ${checkFileType}`);
                }

                fileList.splice(fileList.indexOf(file), 1);
                return false;
            }
        }

        if (checkFileSize > 0) {
            const isLess = file.size / 1024 / 1024 < checkFileSize;
            if (!isLess) {
                if (checkFileSizeMsg) {
                    message.error(checkFileSizeMsg);
                } else {
                    message.error(`File must smaller than ${checkFileSize}MB!`);
                }

                fileList.splice(fileList.indexOf(file), 1);
                return false;
            }
        }
        return true;
    };

    // 上传
    const customUpload = async ({ file, onSuccess, onError }) => {
        const { showErr } = props;
        try {
            const result = await uploadFile(file);
            onSuccess(result, file);
        } catch (e) {
            onError(e);
            if (showErr) {
                showErr(e);
            }
        }
    };

    // 删除文件
    const removeUpload = file => {
        const { fileList, setFileList, onRemove } = props;
        setFileList(fileList);
        if (onRemove) {
            onRemove(file);
        }
        return true;
    };

    const changeUpload = value => {
        const { file, fileList } = value;
        const { setFileList, onChange } = props;
        if (onChange) onChange(value);
        if (!file.status) return;
        if (file.status === 'error') {
            fileList.pop();
        }
        setFileList([...fileList]);
    };

    const { children, dragAble } = props;
    const Component = dragAble ? Upload.Dragger : Upload;
    return (
        <Component
            {...props}
            customRequest={customUpload}
            beforeUpload={checkUpload}
            onRemove={removeUpload}
            onChange={changeUpload}
        >
            {children}
        </Component>
    );
};

export default UploadWork;
